//
//  HomeViewController.m
//  DeviceManage
//
//  Created by zxl on 2020/10/19.
//  Copyright © 2020年 sjl. All rights reserved.
//

#import "HomeViewController.h"

@interface HomeViewController ()
#define SDCycleScrollViewHeight ScreenHeight/3
#define UICollectionViewHeight ScreenHeight/4
#define UITableViewViewHeight ScreenHeight-getRectNavAndStatusHight-SDCycleScrollViewHeight-UICollectionViewHeight
#define UITableViewViewCellHeight ScreenHeight/7
#define CollectionCellHeight 80
@end

@implementation HomeViewController{
      NSString *deviceClassId;
}

-(void)viewDidLoad {
    [super viewDidLoad];
    deviceClassId=@"1";
    _deviceArray=[NSMutableArray array];
    [self getAllDeviceClass];
    [self getAllDeviceByDeviceClassId];
    [self setUpView];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(instancetype)init{
    if (self = [super init]) {
        self.title=@"首页";
        self.tabBarItem.image = [UIImage imageNamed:@"home_tabBar"];
        self.hidesBottomBarWhenPushed = false;
    }
    return self;
}
-(SDCycleScrollView *)bannerScrollView
{
    if (!_bannerScrollView) {
        //构造 5 个图片的数组,用于轮播图控件播放
        NSArray* bannerList=@[@"bannerimg1",@"bannerimg2",@"bannerimg3",
                              @"bannerimg4",@"bannerimg5"];
        //给 bannerScrollView 控件属性赋值
        _bannerScrollView = [SDCycleScrollView cycleScrollViewWithFrame:
                             CGRectMake(0,(getRectNavAndStatusHight), ScreenWidth,SDCycleScrollViewHeight )imageNamesGroup: bannerList];
        _bannerScrollView.pageControlAliment =SDCycleScrollViewPageContolAlimentCenter;
        // 自定义分页控件小圆标颜色
        _bannerScrollView.currentPageDotColor = UIColor.whiteColor;
        _bannerScrollView.layer.masksToBounds=YES;
        _bannerScrollView.bannerImageViewContentMode =
        UIViewContentModeScaleAspectFill;
    }
    return _bannerScrollView;
}
-(UICollectionView *)deviceClassCollectionView{
    if(nil == _deviceClassCollectionView){
        //创建一个 layout 布局类
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        //设置布局方向为垂直流布局
        layout.scrollDirection = UICollectionViewScrollDirectionVertical;
        //创建 collectionView 通过一个布局策略 layout 来创建
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        //执行带 2 个参数的 initWithFrame 方法
    _deviceClassCollectionView=[[UICollectionView alloc]initWithFrame:
                                    CGRectMake(0, getRectNavAndStatusHight+SDCycleScrollViewHeight,
                                               ScreenWidth, UICollectionViewHeight) collectionViewLayout:layout];
        _deviceClassCollectionView.backgroundColor = UIColor.whiteColor;
        _deviceClassCollectionView.scrollEnabled = NO;
        //代理设置
        _deviceClassCollectionView.delegate = self;
        _deviceClassCollectionView.dataSource = self;}
    return _deviceClassCollectionView;

}
-(UITableView *)deviceTableView
{
    if (!_deviceTableView) {
        _deviceTableView = [[UITableView alloc] initWithFrame:
                            CGRectMake(0,getRectNavAndStatusHight+  SDCycleScrollViewHeight+UICollectionViewHeight, ScreenWidth,
                                       UITableViewViewHeight) style:UITableViewStyleGrouped];
        _deviceTableView.backgroundColor =UIColor.whiteColor;
        //代理设置
        _deviceTableView.delegate = self;
        _deviceTableView.dataSource = self;
    }
    return _deviceTableView;
}
//获取所有设备分类列表
-(void)getAllDeviceClass{
    //显示转圈圈控件
    [SVProgressHUD show];
    //执行网络访问请求
    [[NetworkTool shareInstance]requireMethodType:POSTType
                                        URLString:@"findAllDeviceClass"
                                       Parameters:nil
                                          Success:^(NSDictionary *respondDictionary) {
                                              //1.给属性变量进行对象分配
                                              _deviceClassArray = [[NSMutableArray alloc] init];
                                              //2.利用 JSONModel 工具，提取服务器返回的 result 这个 JSON 字符串（它是字典数组变量），并将其转换为 DeviceClass 数组，即将 JSON 数组变量转换成DeviceClass_deviceClassArray
                                              for (NSDictionary *dic in respondDictionary[@"result"]) {
                                                  //3.将每个字典对象转换成 DeviceClass 类对象 model
                                                  DeviceClass *model = [[DeviceClass alloc]initWithDictionary:dic error:nil];
                                                  //4.将 model 加入到数组变量_deviceClassArray 中
                                                  [_deviceClassArray addObject:model];
                                              }
                                              //5.强制刷新集合视图控件，显示最新的设备分类列表
                                              [_deviceClassCollectionView reloadData];
                                              //6.关闭进度条
                                              [SVProgressHUD dismiss];
                                          }
                                          Failure:^(NSError *error) {
                                              [SVProgressHUD dismiss];
                                              [SVProgressHUD showErrorWithStatus:@"设备分类列表获取失败"];
                                          }];
}//获取指定设备分类编号的设备列表
-(void)getAllDeviceByDeviceClassId{
    [SVProgressHUD show];
    // 初始化参数
    NSDictionary *params=@{@"deviceClassId": deviceClassId};
    //执行网络访问请求
    [[NetworkTool shareInstance]requireMethodType:POSTType
                                        URLString:@"findDeviceByDeviceClassId"
                                       Parameters:params
                                          Success:^(NSDictionary *respondDictionary) {
                                              //1.必须删除设备数组中现有的所有设备对象，否则当点击新的设备分类时，原有设备分类下的设备还存在
                                              [self.deviceArray removeAllObjects];
                                              //2.利用 JSONModel 工具，提取服务器返回的 result 这个 JSON 字符串（它是字典数组变量），并将其转换为 Device 数组，即将 JSON 数组变量转换成 Device数组变量_deviceArray
                                              for (NSDictionary *dic in respondDictionary[@"result"]) {
                                                  //3.将每个字典对象转换成 Device 类对象 model
                                                  Device *model = [[Device alloc]initWithDictionary:dic error:nil]; //4.将 model 加入到数组变量_deviceArray 中
                                                  [_deviceArray addObject:model];
                                              }
                                              //5.强制刷新表格视图控件，显示最新的设备列表
                                              [_deviceTableView reloadData];
                                              //6.关闭进度条
                                              [SVProgressHUD dismiss];
                                          }
                                          Failure:^(NSError *error) {
                                              [SVProgressHUD dismiss];
                                              [SVProgressHUD showErrorWithStatus:@"设备列表获取失败"];
                                          }];
}
-(void)setUpView{
    //将轮播图控件变量 bannerScrollView 加入到 self.view 中进行显示
    [self.view addSubview:self.bannerScrollView];
    //将集合视图控件变量 collectionView 加入到 self.view 中进行显示
    [self.view addSubview:self.deviceClassCollectionView];
    //集合视图控件变量 collectionView 注册单元类 DeviceClassCollectionViewCell
    [self.deviceClassCollectionView registerClass:[DeviceClassCollectionViewCell class]
                       forCellWithReuseIdentifier:@"DeviceClassCollectionViewCell"];
    //将表格视图控件变量 deviceTableView 加入到 self.view 中进行显示
    [self.view addSubview:self.deviceTableView];
}
#pragma mark --实现 UICollectionViewDataSource 协议
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView
    numberOfItemsInSection:(NSInteger)section{
    return [_deviceClassArray count];
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                 cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    DeviceClassCollectionViewCell * cell = [collectionView
                                            dequeueReusableCellWithReuseIdentifier:@"DeviceClassCollectionViewCell"
                                            forIndexPath:indexPath];
    DeviceClass *model = _deviceClassArray[indexPath.row];
    [cell setUpCell:model];
    return cell;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout
                                                                   *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat cellWidth = ScreenWidth /3;
    return CGSizeMake(cellWidth, CollectionCellHeight);
}
-(void)collectionView:(UICollectionView *)collectionView
didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    DeviceClass *model=_deviceClassArray[indexPath.row];
    deviceClassId=model.DeviceClassID;
    [self getAllDeviceByDeviceClassId];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [_deviceArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView
        cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DeviceTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell==nil) {
        cell = [[DeviceTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                          reuseIdentifier:@"cell"];
    }
    Device *model = _deviceArray[indexPath.row];
    [cell setUpCell:model];
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView
heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return UITableViewViewCellHeight;
} 
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
